import { useState, useEffect } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { message, Button } from 'antd';
import { userApi } from '@/api';
import './Home.css';

const Home = () => {

  const navigate = useNavigate();
  const [isRegister, setIsRegister] = useState(true);
  const [isSelect, setIsSelect] = useState(false);
  const [isShow,setIsShow] = useState(true)
  const [formData, setFormData] = useState({
    username: '',
    email: '',
    password: ''
  });
  const [loading, setLoading] = useState(false);

  const handleIsRegister = () => {
    setIsRegister(!isRegister);
  }
  // 动态计算是否登录
  useEffect(()=>{
    const token = localStorage.getItem("GS_token")
    if(token){
      setIsShow(false)
    }else{
      setIsShow(true)
    }
  },[])

  const handleInputUsernameChange = (e) => {
    const { name, value } = e.target;
    setFormData({
      ...formData,
      [name]: value
    });
  }

  const handleInputEmailChange = (e) => {
    const { name, value } = e.target;
    setFormData({
      ...formData,
      [name]: value
    });
  }

  const handleInputPasswordChange = (e) => {
    const { name, value } = e.target;
    setFormData({
      ...formData,
      [name]: value
    });
  }

  const handleIsSelectChange = (e) => {
    // const { isSelect, value } = e.target;
    setIsSelect(e.target.checked);
  }

  const handleSubmit = async (e) => {
    e.preventDefault();
    console.log('表单数据',formData,isSelect);
    // 表单验证
    if (!formData.username || !formData.password || (isRegister && !formData.email)) {
      message.error('请填写所有必填字段');
      return;
    }
    
    setLoading(true);
    
    try {
      if (isRegister) {
        // 注册
        if (!isSelect) {
          message.warning('请同意条款和条件');
          return;
        }
        await userApi.register(formData);
        message.success('注册成功，请登录');
        setIsRegister(false);
      } else {
        // 登录
        const response = await userApi.login({
          username: formData.username,
          password: formData.password
        });
        
        // 保存token和用户信息
        localStorage.setItem('GS_token', response.token);
        localStorage.setItem('GS_user', JSON.stringify(response.user));
        setIsShow(false)
        message.success('登录成功');
        navigate('/dashboard');
      }
    } catch (error) {
      // 服务器返回的错误
      if (error.response.status === 403) {
        message.error('用户未注册，请先注册');
      } else if (error.response.status === 401) {
        message.error('用户名或密码错误');
      } else {
        message.error(error.response.data.message || '注册失败');
      }
    } finally {
      setLoading(false);
    }
  }

  return (
    <>
      <section id="home" className="w3l-banner py-5">
        <div className="container py-lg-5 py-md-4 mt-lg-0 mt-5">
          <div className="row align-items-center py-lg-5 py-4 mt-4">
            <div className="col-lg-6 col-sm-12">
              <h3 className="mb-md-4 mb-3">基于海洋生态数据的可视化产业发展评估系统研究与实现</h3>
              <p>我们提供专业的海洋生态数据可视化系统，帮助您的企业在竞争激烈的市场中脱颖而出。</p>
            </div>
            {isShow && <div className="col-lg-5 offset-lg-1 col-md-8 col-sm-10 mt-lg-0 mt-5">
              <div className="banner-form-w3">
                <form action="#" method="post">
                  <h5 className="mb-4" >{isRegister ? '立即注册' : '立即登录'}</h5>
                  <div className="form-style-w3ls">
                    <input 
                      placeholder="用户名" 
                      name="username" 
                      type="text" 
                      required 
                      value={formData.username}
                      onChange={handleInputUsernameChange}
                    />
                    {isRegister && <input placeholder="您的邮箱" name="email" type="email" required value={formData.email} onChange={handleInputEmailChange}/>}
                    <input placeholder="密码" name="password" type="password" required value={formData.password} onChange={handleInputPasswordChange}/>
                    <div className="form-group">
                      {isRegister && <label className="check-remember container1">
                        <input type="checkbox" value={isSelect} onChange={handleIsSelectChange}/>
                        <span className="checkmark"></span>
                      </label>}
                      {isRegister && <p className="remember">我同意 <a href="">条款和条件</a></p>}
                      <a className="remember-a" onClick={()=> handleIsRegister()}>{!isRegister ? '未注册？立即注册' : '已注册？立即登录'}</a>
                    </div>
                    <Button className="btn btn-primary w-100" size='large' loading={loading} onClick={handleSubmit}>{isRegister ? '注册' : '登录'}</Button>
                  </div>
                </form>
              </div>
            </div>}
          </div>
        </div>
      </section>
      <div className="position-relative">
        <div className="shape overflow-hidden">
          <svg viewBox="0 0 2880 48" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M0 48H1437.5H2880V0H2160C1442.5 52 720 0 720 0H0V48Z" fill="currentColor"></path>
          </svg>
        </div>
      </div>
    </>
  );
};

export default Home; 